<template>
    <div class="app-container">
        <!-- 步骤导航 -->
        <div class="steps-container">
            <button @click="test">测试</button>
            <button @click="router.back">返回</button>
            <el-steps :active="activeStep" finish-status="success" align-center>
                <el-step title="基础信息" />
                <el-step title="配置考核指标" />
            </el-steps>
        </div>

        <!-- 基础信息模块 -->
        <div v-if="activeStep === 0" class="form-container">
            <el-form :model="baseForm" label-width="120px" label-position="right">

                <el-form-item label="*考核组名称" class="required-field">
                    <el-input v-model="baseForm.groupName" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="*考核周期类型" class="required-field">
                    <el-select v-model="baseForm.cycleType" placeholder="请选择" clearable>
                        <el-option label="月度" value="月度" />
                        <el-option label="季度" value="季度" />
                        <el-option label="年度" value="年度" />
                    </el-select>
                </el-form-item>

                <el-form-item label="考核月份">
                    <el-date-picker v-model="baseForm.month" type="month" placeholder="选择月份" value-format="YYYY-MM"
                        format="YYYY年MM月" style="width: 100%" />
                </el-form-item>

                <el-form-item label="考核周期" class="required-field">
                    <el-input v-model="baseForm.cycle" disabled placeholder="请输入" />
                </el-form-item>

                <el-form-item label="考核范围">
                    <!-- <el-input v-model="baseForm.scope" placeholder="请选择范围">
                    </el-input> -->
                    <el-select v-model="baseForm.scope" placeholder="请选择" clearable>
                        <el-option v-for="dept in depts" :key="dept.deptId" :label="dept.deptName"
                            :value="dept.deptId" />

                    </el-select>
                </el-form-item>

                <el-form-item label="考核人" class="required-field">
                    <el-select v-model="baseForm.assessor" placeholder="请选择" clearable>
                        <el-option v-for="assessor in assessors" :key="assessor.userId" :label="assessor.nickName"
                            :value="assessor.userId" />

                    </el-select>
                </el-form-item>

                <el-form-item label="考核说明">
                    <el-input v-model="baseForm.description" type="textarea" :rows="4" placeholder="请输入说明" />
                </el-form-item>

                <el-form-item class="form-buttons">
                    <el-button type="primary" size="large" @click="nextStep">保存</el-button>
                    <el-button size="large" @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 配置考核指标模块 -->
        <div v-if="activeStep === 1" class="indicator-container">
            <div class="indicator-header">


                <el-button type="primary" icon="Plus" class="select-indicator-button" size="large"
                    @click="showIndicatorDialog = true">
                    选择指标
                </el-button>
            </div>

            <!-- 指标分类表格 - 仅在有指标时显示 -->
            <template v-for="(category, idx) in indicators" :key="idx">
                <div v-if="category.items.length > 0" class="indicator-group">
                    <div class="group-header">
                        <span class="category-title">{{ category.type }}</span>
                    </div>

                    <el-table :data="category.items" border size="large" style="width: 100%; margin-top: 15px"
                        empty-text="暂无指标数据">
                        <el-table-column prop="name" label="指标名称" width="200" />
                        <el-table-column prop="type" label="指标类别" width="150" />
                        <el-table-column prop="rule" label="指标规则" min-width="350">
                            <template #default="{ row }">
                                <div>{{ formatRule(row.rule) }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="scoreMaxline" label="评分上限" width="120" />
                        <el-table-column prop="remark" label="备注" width="150" />
                    </el-table>
                </div>
            </template>

            <div class="indicator-buttons">
                <el-button type="primary" size="large" @click="saveIndicators">保存</el-button>
                <el-button size="large" @click="prevStep">取消</el-button>
            </div>
        </div>

        <!-- 选择指标弹窗 -->
        <el-dialog v-model="showIndicatorDialog" title="选择指标" width="60%" top="5vh" class="indicator-dialog">
            <div class="indicator-dialog-content">
                <div class="search-section">
                    <el-input v-model="searchKeyword" placeholder="请输入关键字" clearable size="large"
                        style="width: 300px; margin-right: 15px" />
                    <el-link type="primary" :underline="false" style="font-size: 16px">配置考核指标</el-link>
                </div>

                <el-table ref="selectionTable" :data="availableIndicators" border size="large"
                    style="width: 100%; margin: 25px 0" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column prop="name" label="指标名称" width="220" />
                    <el-table-column prop="type" label="指标类别" width="220" />
                    <el-table-column prop="scoreMaxline" label="评分上限" width="140" />
                </el-table>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showIndicatorDialog = false" size="large">取消</el-button>
                    <el-button type="primary" @click="confirmSelection" size="large">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ref, reactive, computed, watch } from 'vue'
import { addPlan } from "@/api/jixiao/plan"
import { assessJoinType, addmidPlanAssess, delPlanAssess, updatePlanAssess, getDept } from '@/api/jixiao/kaohejihua/bianji'
import { getApprovers } from '@/api/approval/approvalForm/approvalForm'
import router from '../../../router'
import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
// 步骤状态
const activeStep = ref(0)

// 基础表单数据
const baseForm = reactive({
    groupName: '',
    cycleType: '月度',
    month: '2022-03',
    cycle: '',
    scope: '1',
    assessor: '', // 考核人
    description: ''
})


// 监听 cycleType 和 month 的变化，自动计算 cycle
watch(
    () => [baseForm.cycleType, baseForm.month],
    ([newCycleType, newMonth]) => {
        if (!newMonth) return;

        try {
            // 统一格式化日期为 "YYYY-MM"
            const formattedMonth = formatMonthString(newMonth);
            if (!formattedMonth) return; // 如果格式化失败，不计算

            const [year, month] = formattedMonth.split('-').map(Number);
            let endDate;

            switch (newCycleType) {
                case '月度':
                    endDate = new Date(year, month, 0); // month + 1 月的最后一天
                    break;
                case '季度':
                    endDate = new Date(year, month + 2, 0); // month + 3 月的最后一天
                    break;
                case '半年度':
                    endDate = new Date(year, month + 5, 0); // month + 6 月的最后一天
                    break;
                case '年度':
                    endDate = new Date(year, month + 11, 0); // month + 12 月的最后一天
                    break;
                default:
                    return;
            }

            // 输出格式化为 "YYYY年MM月--YYYY年MM月"
            const startStr = formatOutputDate(newMonth); // 保持原始格式
            const endStr = formatOutputDate(
                `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}`
            );
            baseForm.cycle = `${startStr}--${endStr}`;
        } catch (e) {
            console.error('计算 cycle 出错:', e);
        }
    },
    { immediate: true }
);

// 辅助函数：将不同格式的月份统一转为 "YYYY-MM"
function formatMonthString(monthStr) {
    // 处理 "2022-01" 格式
    if (/^\d{4}-\d{2}$/.test(monthStr)) {
        return monthStr;
    }
    // 处理 "2022年01月" 格式
    if (/^\d{4}年\d{2}月$/.test(monthStr)) {
        return monthStr.replace('年', '-').replace('月', '');
    }
    console.error('月份格式不支持:', monthStr);
    return null;
}

// 辅助函数：根据输入格式输出对应格式的日期
function formatOutputDate(dateStr) {
    // 如果输入是 "2022年01月" 格式，输出也保持该格式
    if (/^\d{4}年\d{2}月$/.test(dateStr)) {
        const [year, month] = dateStr.replace('年', '-').replace('月', '').split('-');
        return `${year}年${month}月`;
    }
    // 默认输出 "YYYY-MM" 格式
    return dateStr;
}


// 指标配置数据
// const calculationMethod = ref('加和计算')
const showIndicatorDialog = ref(false)
const searchKeyword = ref('')
const selectedIndicators = ref([])

// 可用指标列表 - 基于第三张图
let availableIndicators = ref([
    { id: 1, name: '工作效率', typeId: '1', type: '指标类别', scoreLimit: 80, remark: '备注1' },
    { id: 2, name: '服务质量', typeId: '1', type: '指标类别', scoreLimit: 80, remark: '备注2' },
    { id: 3, name: '售前咨询', typeId: '1', type: '指标类别', scoreLimit: 80, remark: '备注3' },
    { id: 4, name: '订单处理', typeId: '2', type: '指标类别', scoreLimit: 80, remark: '备注4' },
    { id: 5, name: '售后支持', typeId: '2', type: '指标类别', scoreLimit: 80, remark: '备注5' },
    { id: 6, name: '测试覆盖率', typeId: '3', type: '指标类别', scoreLimit: 80, remark: '备注6' },
    { id: 7, name: '验收合格率', typeId: '3', type: '指标类别', scoreLimit: 80, remark: '备注7' },
    { id: 8, name: '市场推广', typeId: '4', type: '指标类别', scoreLimit: 80, remark: '备注8' }
])
const flag = ref()

const assessors = ref([])
const depts = ref([])
function test() {
    console.log('测试')
    //   addp()//添加考核计划





    // getAllIndicators()//获取所有指标

}
function getassessors() {
    getApprovers().then(response => {
        // console.log('考核人', response.rows)
        assessors.value = response.rows
    })
}
function getDepts() {
    getDept().then(response => {
        console.log('部门', response)
        depts.value = response.rows
    })
}
function del() {
    delPlanAssess(selectedIndicatorId.value).then(response => {
        console.log('删除的业绩指标id', response)
    })
}
//更新考核计划
function updatePlan() {
    updatePlanAssess({
        id: selectedIndicatorId.value,
        name: baseForm.groupName,
        cycleType: baseForm.cycleType,
        startDate: `${baseForm.month}-01`,
        cycle: baseForm.cycle,
        departmentId: baseForm.scope,
        assessorId: baseForm.assessor,
        performanceaccessmentId: baseForm.description
    }).then(response => {
        console.log('更新考核计划', response)
        ElMessage.success("更新成功")
    })
}


//查询所有考核指标
function getAllIndicators() {
    //   console.log('查询所有指标')

    assessJoinType().then(response => {
        // console.log(response.rows)
        availableIndicators = response.rows
    })
}
onMounted(() => {
    getAllIndicators()
    //接收参数
    getFlag()
    //获取所有的考核人
    getassessors()
    
        getDepts()//获取所有部门

})
function getFlag() {
    console.log('接收的参数', route.query)
    if (route.query.id) {
        flag.value = '编辑'
        console.log(flag.value)
        selectedIndicatorId.value = route.query.id
        baseForm.groupName = route.query.groupName
        baseForm.cycleType = route.query.cycleType
        baseForm.month = route.query.month
        baseForm.cycle = route.query.cycle
        baseForm.scope = route.query.scope
        baseForm.assessor = route.query.assessor
        baseForm.description = route.query.description
    } else {
        flag.value = '新增'
        console.log(flag.value)
    }
}
// 当前配置的指标（分组） - 基于第二张图
const indicators = ref([
    {
        type: '销售指标',
        items: [
            { id: 1, name: '工作效率', typeId: '1', type: '销售指标', scoreMaxline: 80, remark: '备注1' },
            { id: 2, name: '服务质量', typeId: '1', type: '销售指标', scoreLimit: 80, remark: '备注2' },
            { id: 3, name: '售前咨询', typeId: '1', type: '销售指标', scoreMaxline: 80, remark: '备注3' }
        ]
    }
])

// 步骤控制方法
const nextStep = async () => {
    if (activeStep.value < 1) activeStep.value++
    else {
        if (flag.value == '新增') {
            console.log('所有步骤已完成')
            await addp() // 提交考核计划
            //添加业绩指标  1获取新增的考核计划id  2利用的绩效指标数组  3循环执行添加请求
            console.log('新增的考核计划id', selectedIndicatorId.value)
            console.log('新增的绩效指标数组', idArray.value)

            for (let i = 0; i < idArray.value.length; i++) {
                addmidPlanAssess({
                    planId: selectedIndicatorId.value,
                    assessId: idArray.value[i]
                }).then(response => {
                    console.log('新增的业绩指标id', response)
                })
            }
        } else {
            //这个是编辑
            //1 进行编辑考核计划表 2删除原来的绩效指标 3添加新的绩效指标
            del()
            updatePlan()
            console.log('考核计划id', selectedIndicatorId.value)
            console.log('新增的绩效指标数组', idArray.value)

            for (let i = 0; i < idArray.value.length; i++) {
                addmidPlanAssess({
                    planId: selectedIndicatorId.value,
                    assessId: idArray.value[i]
                }).then(response => {
                    console.log('业绩指标id', response)
                })
            }

        }


        router.push('/jixiao/plan')//跳转到考核计划列表页面
    }
}
const prevStep = () => {
    if (activeStep.value > 0) activeStep.value--
}
const resetForm = () => {
    Object.keys(baseForm).forEach(key => {
        if (key === 'cycle') baseForm[key] = '月度'
        else if (key === 'month') baseForm[key] = '2022年3月'
        else if (key === 'scope') baseForm[key] = '全部成员'
        else baseForm[key] = ''
    })
}
const selectedIndicatorId = ref(null)
//上传考核计划plan
async function addp() {
    // console.log('上传考核计划')
    const baseFormData = {
        name: baseForm.groupName,
        cycleType: baseForm.cycleType,
        startDate: `${baseForm.month}-01`,
        cycle: baseForm.cycle,
        departmentId: baseForm.scope,
        assessorId: baseForm.assessor,
        performanceaccessmentId: baseForm.description
    }


    await addPlan(baseFormData).then(response => {
        // console.log(response)
        selectedIndicatorId.value = response
        // console.log('``````````````````````新增的考核计划id',selectedIndicatorId.value)
        ElMessage.success("新增成功")
    })
}



// 指标选择对话框相关
// const filteredIndicators = computed(() => {
//   if (!searchKeyword.value) return availableIndicators
//   const keyword = searchKeyword.value.toLowerCase()
//   return availableIndicators.filter(indicator => 
//     indicator.name.toLowerCase().includes(keyword) || 
//     indicator.category.toLowerCase().includes(keyword)
//   )
// })

const idArray = ref([1, 2])

const handleSelectionChange = (selection) => {
    selectedIndicators.value = selection
    console.log('选中指标:', selectedIndicators.value)
    idArray.value = selectedIndicators.value.map(item => item.id);
    console.log('选中指标ID数组:', idArray.value);

    indicators.value = selectedIndicators.value.reduce((result, item) => {
        // 查找是否已存在该类型分组
        const group = result.find(g => g.type === item.type);

        if (group) {
            group.items.push(item);
        } else {
            result.push({
                type: item.type,
                items: [item]
            });
        }
        return result;
    }, [])

    console.log(indicators.value);
}



const confirmSelection = () => {
    // if (selectedIndicators.value.length === 0) {
    //     showIndicatorDialog.value = false
    //     return
    // }

    // selectedIndicators.value.forEach(selected => {
    //     // 根据类别添加到对应分组
    //     let categoryFound = false

    //     if (selected.category.includes('销售')) {
    //         const category = indicators.value.find(cat => cat.name === '销售指标')
    //         if (!category.items.some(item => item.id === selected.id)) {
    //             category.items.push(createIndicatorData(selected))
    //         }
    //         categoryFound = true
    //     }

    //     if (selected.category.includes('服务') && !categoryFound) {
    //         const category = indicators.value.find(cat => cat.name === '服务指标')
    //         if (!category.items.some(item => item.id === selected.id)) {
    //             category.items.push(createIndicatorData(selected))
    //         }
    //         categoryFound = true
    //     }

    //     if (!categoryFound) {
    //         const category = indicators.value.find(cat => cat.name === '业务指标')
    //         if (!category.items.some(item => item.id === selected.id)) {
    //             category.items.push(createIndicatorData(selected))
    //         }
    //     }
    // })

    showIndicatorDialog.value = false
    // searchKeyword.value = ''
    // selectedIndicators.value = []
}



// 辅助函数
const formatRule = (rule) => {
    return rule.replaceAll(',', ', ')
}

const saveIndicators = () => {
    console.log('保存指标配置:', indicators.value)
    nextStep()
}
</script>

<style scoped>
.app-container {
    padding: 25px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.steps-container {
    margin-bottom: 40px;
    padding: 25px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.form-container,
.indicator-container {
    background-color: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.form-container .el-form {
    width: 60%;
    min-width: 750px;
    margin: 0 auto;
}

.el-form-item {
    margin-bottom: 25px;
}

.form-buttons {
    margin-top: 45px;
    text-align: center;
}

.required-field :deep(.el-form-item__label)::before {
    content: "*";
    color: #F56C6C;
    margin-right: 4px;
}

.indicator-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.section-title {
    margin-right: 20px;
    font-weight: bold;
    font-size: 18px;
    color: #303133;
}

.select-indicator-button {
    margin-right: 15px;
}

.indicator-group {
    margin-bottom: 45px;
}

.group-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.category-title {
    font-weight: bold;
    font-size: 18px;
    margin-right: 20px;
    color: #1a1a1a;
}

.edit-category {
    font-size: 15px;
    color: #409EFF;
}

.indicator-buttons {
    margin-top: 45px;
    text-align: center;
}

.search-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
}

.indicator-dialog-content {
    max-height: 60vh;
    overflow-y: auto;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 1200px) {
    .form-container .el-form {
        width: 80%;
        min-width: 600px;
    }
}

@media (max-width: 768px) {
    .form-container .el-form {
        width: 95%;
        min-width: auto;
    }

    .indicator-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .calculation-section {
        margin-bottom: 20px;
        width: 100%;
    }

    .select-indicator-button {
        width: 100%;
        margin-top: 10px;
    }

    .group-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .edit-category {
        margin-top: 8px;
    }
}
</style>